/*
 * @Description: 编辑档案分类弹窗组件
 * @Author: Rfan
 * @Date: 2022-05-31 15:25:56
 * @LastEditTime: 2022-06-05 11:52:43
 */

import { Button, Form, Modal } from 'antd';
import { FC, useEffect } from 'react';
import ItemForm from './common/ItemForm';
import { getListItemValue } from '@/utils/list';
import { useArchiveClassifyContext } from '../../contexts/ArchiveClassifyContext';
import type { ICommonDialog } from '@/interfaces/global';

interface EditItemDialogProps extends ICommonDialog {
  data: any;
}

const EditItemDialog: FC<EditItemDialogProps> = (props) => {
  const { visible, data, onClose } = props;
  const { selectAT, selectVerId, classifyList, editClassifyFunc } = useArchiveClassifyContext();
  const [form] = Form.useForm();

  useEffect(() => {
    // 表单字段暂为小写，待修复后去掉
    const _info: any = {};
    for (const key in data) {
      _info[key.toLocaleLowerCase()] = data[key];
    }
    form.setFieldsValue(_info);
    // form.setFieldsValue(data);
  }, [visible]);

  // 提交表单
  const submitFunc = () => {
    form.submit();
  };

  // 新增档案类型
  const onFinish = (values: any) => {
    editClassifyFunc({ ...data, ...values }).then(() => {
      onCancel();
    });
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  const onCancel = () => {
    onClose();
  };

  return (
    <Modal
      destroyOnClose
      title="编辑分类"
      visible={visible}
      width={600}
      onCancel={onCancel}
      footer={[
        <Button key="back" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={submitFunc}>
          保存
        </Button>
      ]}
    >
      <Form
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        preserve={false}
        form={form}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        {data?.pid ? (
          <Form.Item label="上级分类">
            {getListItemValue(data.pid, classifyList, 'cName')}
          </Form.Item>
        ) : (
          <Form.Item label="级别">顶层（最高级）</Form.Item>
        )}
        <ItemForm />
      </Form>
    </Modal>
  );
};

export default EditItemDialog;
